package com.xbongbong.pro.rabbitmq.producer.impl;

import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.MessageErrorCodeEnum;
import com.xbongbong.pro.message.enums.SmsSendFromTypeEnum;
import com.xbongbong.pro.rabbitmq.binders.SmsProducerBinder;
import com.xbongbong.pro.rabbitmq.producer.SmsProducer;
import com.xbongbong.pro.sms.pojo.dto.SmsRabbitMqDTO;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author youli.chen
 * @version v1.0
 * @date 2019/3/19 15:37
 * @since v1.0
 */
@Service("smsProducer")
@EnableBinding(SmsProducerBinder.class)
public class SmsProducerImpl implements SmsProducer {

    private static final String HEADER_NAME = "sendType";

    @Resource
    private SmsProducerBinder smsBinder;

    @Override
    public void sendSms(SmsSendFromTypeEnum sendFromType, SmsRabbitMqDTO smsRabbitMqDTO) throws XbbException {
        MessageBuilder messageBuilder;
        MessageHeaderAccessor messageHeaderAccessor = new MessageHeaderAccessor();
        Object header;
        switch (sendFromType) {
            case SMS_SEND:
                header = SmsSendFromTypeEnum.SMS_SEND;
                messageHeaderAccessor.setHeader(HEADER_NAME, header);
                messageBuilder = MessageBuilder.withPayload(smsRabbitMqDTO).setHeaders(messageHeaderAccessor);
                smsBinder.smsOutput().send(messageBuilder.build());
                break;
            case SMS_SEND_FOR_BUSINESS:
                header = SmsSendFromTypeEnum.SMS_SEND_FOR_BUSINESS;
                messageHeaderAccessor.setHeader(HEADER_NAME, header);
                messageBuilder = MessageBuilder.withPayload(smsRabbitMqDTO).setHeaders(messageHeaderAccessor);
                smsBinder.smsOutput().send(messageBuilder.build());
                break;
            case SMS_RE_SEND:
                header = SmsSendFromTypeEnum.SMS_RE_SEND;
                messageHeaderAccessor.setHeader(HEADER_NAME, header);
                messageBuilder = MessageBuilder.withPayload(smsRabbitMqDTO).setHeaders(messageHeaderAccessor);
                smsBinder.smsOutput().send(messageBuilder.build());
                break;
            case UNKNOWN:
                throw new XbbException(MessageErrorCodeEnum.API_ERROR_380001);
            default:
                break;
        }
    }
}
